package projetomsn.Client.UI;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;


import java.util.NoSuchElementException;
import java.util.ResourceBundle;

import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import projetomsn.Client.Key;
import projetomsn.Client.ServerInterface.ClientManager;

import projetomsn.Client.UI.FontConfig.FontHTML;
import projetomsn.Client.UI.FontConfig.FontStyleFrame;
import projetomsn.Client.Settings.SettingsFile;
import projetomsn.Client.UI.sounds.Sound;
import projetomsn.Client.UI.sounds.SoundManager;
import projetomsn.Server.ServerSettings;

/**
 * Classe para gerar a janela de conversação
 * @author Greg
 */
public class ChatWithAllFrame extends javax.swing.JFrame {

    /**
     * Gerenciador de mensagens 
     */
    private ClientManager clientManager;
    /**
     * Atributo do nome do usuário
     */
    public String userName = "";
    /**
     * Atributo com nome do amigo
     */
    private String friendName = "null";
    /**
     * Atributo de mensagem recebida
     */
    private StringBuilder messageSentReceived;
    /**
     * Atributo de mensagem a ser enviada
     */
    private StringBuilder messageToSend;
    /**
     * Atributo de fonte do nome do usuário
     */
    private FontHTML myNameFont;
    /**
     * Atributo de fonte do separador, nome da mensagem, do usuário
     */
    private FontHTML mySeparatorFont;
    /**
     * Atributo de fonte da mensagem do usuário
     */
    private FontHTML myTextFont;
    /**
     * Atributo de fonte do nome do amigo
     */
    private FontHTML friendNameFont;
    /**
     * Atributo de fonte do separado, nome da mensagem, do amigo
     */
    private FontHTML friendSeparatorFont;
    /**
     * Atributo de fonte da mensagem do amigo
     */
    private FontHTML friendTextFont;
    /**
     * Parte inicial do HTML
     */
    private String header = ""
            + "<html>"
            + "<body>";
    /**
     * Parte final do HTML
     */
    private String body = ""
            + "</body>"
            + "</html>";
    /**
     * ArrayList de emoticons
     */
    private ArrayList<String> emoticonsCode;//used to record emoticons code
    /**
     * Variavel de limitação de caracteres na mensagem
     */
    int characterRemaining = 150;
    /**
     * Boolean de inserção de emoticons
     */
    private boolean canInsertEmoticons = true;
    /**
     * 
     */
    private KeyEvent inputMessageEvent;
    /**
     * Variavel para gerar log
     */
    private static Logger log = Logger.getLogger(ChatWithAllFrame.class.getName());
    //String language;
    //private ResourceBundle myResources;
    /**
     * Cria internacionalização
     */
    private ResourceBundle myResources =
            ResourceBundle.getBundle("Properties.messages", Locale.getDefault());

    /** 
     * Creates new form ChatFrame
     */
    public ChatWithAllFrame(ClientManager manager) {
        super("Chat Frame");

        /*Locale.getDefault();
        
        if(Locale.getDefault().toString().equalsIgnoreCase("pt_BR"))
        language = "Properties/messages";
        else if(Locale.getDefault().toString().equalsIgnoreCase("en_US"))
        language = "Properties/messages_en_US";
        
        myResources =
        ResourceBundle.getBundle(language , Locale.getDefault());*/

        initComponents();
        initFontStyles();
        initUser();
        clientManager = (ClientManager) manager;
        displayMessage.setContentType("text/html");

        messageSentReceived = new StringBuilder();
        messageToSend = new StringBuilder("");
        getTextSettings();
        setInputMessageSetStyle();
        setTitle("Chat Frame(" + myResources.getString("chat.titulo") + userName + " )");

        emoticonsCode = new ArrayList<String>(150);
        initEmoticonsCode();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    /**
     * Inicializa componentes gerados pelo netbeans
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        chatBackgroundPanel = new javax.swing.JPanel();
        sendButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        displayMessage = new javax.swing.JTextPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        inputMessage = new javax.swing.JTextPane();
        emoticonsButton = new javax.swing.JButton();
        fontButton = new javax.swing.JButton();
        characterRemainingLabel = new javax.swing.JLabel();
        characterNumberLabel = new javax.swing.JLabel();
        updateSettingsButton = new javax.swing.JButton();
        chatMenu = new javax.swing.JMenuBar();
        settingsMenu = new javax.swing.JMenu();
        textMenu = new javax.swing.JMenu();
        fontMenu = new javax.swing.JMenu();
        styleMenuItem = new javax.swing.JMenuItem();
        addMenu = new javax.swing.JMenu();
        jMenu1 = new javax.swing.JMenu();
        evilMenuItem = new javax.swing.JMenuItem();
        grinMenuItem = new javax.swing.JMenuItem();
        happyMenuItem = new javax.swing.JMenuItem();
        smileMenuItem = new javax.swing.JMenuItem();
        surprisedMenuItem = new javax.swing.JMenuItem();
        tongueMenuItem = new javax.swing.JMenuItem();
        unhappyMenuItem = new javax.swing.JMenuItem();
        winkMenuItem = new javax.swing.JMenuItem();
        wiiMenuItem = new javax.swing.JMenuItem();

        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        chatBackgroundPanel.setBackground(new java.awt.Color(222, 227, 238));
        chatBackgroundPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        sendButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/sendMessage.png"))); // NOI18N
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("Properties/messages"); // NOI18N
        sendButton.setToolTipText(bundle.getString("chat.button.enviar")); // NOI18N
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        displayMessage.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(234, 235, 237), 3, true));
        displayMessage.setEditable(false);
        displayMessage.setDoubleBuffered(true);
        jScrollPane1.setViewportView(displayMessage);

        inputMessage.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(224, 227, 240), 3));
        inputMessage.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputMessageKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(inputMessage);

        emoticonsButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_menu.gif"))); // NOI18N
        emoticonsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                emoticonsButtonActionPerformed(evt);
            }
        });

        fontButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Font/style_1.png"))); // NOI18N
        fontButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fontButtonActionPerformed(evt);
            }
        });

        characterRemainingLabel.setBackground(new java.awt.Color(255, 255, 255));
        characterRemainingLabel.setFont(new java.awt.Font("Tempus Sans ITC", 0, 18));
        characterRemainingLabel.setText(bundle.getString("chat.lable.caracteres.restantes")); // NOI18N

        characterNumberLabel.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18));
        characterNumberLabel.setText("150");

        updateSettingsButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/update.png"))); // NOI18N
        updateSettingsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateSettingsButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout chatBackgroundPanelLayout = new javax.swing.GroupLayout(chatBackgroundPanel);
        chatBackgroundPanel.setLayout(chatBackgroundPanelLayout);
        chatBackgroundPanelLayout.setHorizontalGroup(
            chatBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(chatBackgroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(chatBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(chatBackgroundPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                        .addGap(1, 1, 1))
                    .addGroup(chatBackgroundPanelLayout.createSequentialGroup()
                        .addComponent(characterRemainingLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(characterNumberLabel)
                        .addGap(510, 510, 510))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 775, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(chatBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(updateSettingsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(chatBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(fontButton, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                        .addComponent(emoticonsButton, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                        .addComponent(sendButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 55, Short.MAX_VALUE)))
                .addContainerGap(12, Short.MAX_VALUE))
        );
        chatBackgroundPanelLayout.setVerticalGroup(
            chatBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(chatBackgroundPanelLayout.createSequentialGroup()
                .addGroup(chatBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, chatBackgroundPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(chatBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(characterRemainingLabel)
                            .addComponent(characterNumberLabel))
                        .addGap(11, 11, 11))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, chatBackgroundPanelLayout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(updateSettingsButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(fontButton)
                        .addGap(18, 18, 18)))
                .addGroup(chatBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(chatBackgroundPanelLayout.createSequentialGroup()
                        .addComponent(emoticonsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE))
                .addContainerGap())
        );

        chatMenu.setBackground(new java.awt.Color(157, 157, 212));
        chatMenu.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, new java.awt.Color(229, 229, 250)));

        settingsMenu.setBackground(new java.awt.Color(157, 157, 212));
        settingsMenu.setForeground(new java.awt.Color(255, 255, 255));
        settingsMenu.setText(bundle.getString("chat.menu.configuracoes")); // NOI18N
        settingsMenu.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14));

        textMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Font/text.png"))); // NOI18N
        textMenu.setText(bundle.getString("chat.menuitem.texto")); // NOI18N

        fontMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Font/font.png"))); // NOI18N
        fontMenu.setText(bundle.getString("chat.menuitem.fonte")); // NOI18N

        styleMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Font/style.png"))); // NOI18N
        styleMenuItem.setText(bundle.getString("chat.menuitem.estilo")); // NOI18N
        styleMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                styleMenuItemActionPerformed(evt);
            }
        });
        fontMenu.add(styleMenuItem);

        textMenu.add(fontMenu);

        settingsMenu.add(textMenu);

        chatMenu.add(settingsMenu);

        addMenu.setBackground(new java.awt.Color(157, 157, 212));
        addMenu.setForeground(new java.awt.Color(255, 255, 255));
        addMenu.setText(bundle.getString("chat.menu.adicionar")); // NOI18N
        addMenu.setFont(new java.awt.Font("Tempus Sans ITC", 1, 14));

        jMenu1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_menu.gif"))); // NOI18N
        jMenu1.setText(bundle.getString("chat.menuitem.emoticons")); // NOI18N

        evilMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_evilgrin.png"))); // NOI18N
        evilMenuItem.setText(bundle.getString("chat.menuitem.emoticon.mal")); // NOI18N
        evilMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                evilMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(evilMenuItem);

        grinMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_grin.png"))); // NOI18N
        grinMenuItem.setText(bundle.getString("chat.menuitem.emoticon.ironico")); // NOI18N
        grinMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                grinMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(grinMenuItem);

        happyMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_happy.png"))); // NOI18N
        happyMenuItem.setText(bundle.getString("chat.menuitem.emoticon.feliz")); // NOI18N
        happyMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                happyMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(happyMenuItem);

        smileMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_smile.png"))); // NOI18N
        smileMenuItem.setText(bundle.getString("chat.menuitem.emoticon.sorriso")); // NOI18N
        smileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                smileMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(smileMenuItem);

        surprisedMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_surprised.png"))); // NOI18N
        surprisedMenuItem.setText(bundle.getString("chat.menuitem.emoticon.surpreso")); // NOI18N
        surprisedMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                surprisedMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(surprisedMenuItem);

        tongueMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_tongue.png"))); // NOI18N
        tongueMenuItem.setText(bundle.getString("chat.menuitem.emoticon.lingua")); // NOI18N
        tongueMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tongueMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(tongueMenuItem);

        unhappyMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_unhappy.png"))); // NOI18N
        unhappyMenuItem.setText(bundle.getString("chat.menuitem.emoticon.triste")); // NOI18N
        unhappyMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                unhappyMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(unhappyMenuItem);

        winkMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_wink.png"))); // NOI18N
        winkMenuItem.setText(bundle.getString("chat.menuitem.emoticon.wink")); // NOI18N
        winkMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                winkMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(winkMenuItem);

        wiiMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_waii.png"))); // NOI18N
        wiiMenuItem.setText(bundle.getString("chat.menuitem.emoticon.waii")); // NOI18N
        wiiMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                wiiMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(wiiMenuItem);

        addMenu.add(jMenu1);

        chatMenu.add(addMenu);

        setJMenuBar(chatMenu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(chatBackgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(chatBackgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Evento gerado botão de envio de mensagem
     * @param evt 
     */
    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed
        // TODO add your handling code here:

        String message = inputMessage.getText();
        if (!message.equals("")) {
            try {
                clientManager.send("null" + ServerSettings.marca + userName,
                        Emoticon.addEmoticonsToMessage(message, emoticonsCode)); // manda mensagem

                inputMessage.setText(""); // limpa inputArea

                SoundManager.play(Sound.SEND);

            } catch (UnsupportedAudioFileException ex) {
                Logger.getLogger(ChatWithAllFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (LineUnavailableException ex) {
                Logger.getLogger(ChatWithAllFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
            }
        }
        characterRemaining = 150;
        characterNumberLabel.setText("" + characterRemaining);

        log.info(myResources.getString("chat.log.mensagem.enviada"));

    }//GEN-LAST:event_sendButtonActionPerformed

    /**
     * Menu de seleção do estilo de fonte
     * @param evt 
     */
    private void styleMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_styleMenuItemActionPerformed
        // TODO add your handling code here:
        new FontStyleFrame("ChatFontSettings");
    }//GEN-LAST:event_styleMenuItemActionPerformed

    /**
     * Evento de seleção de fonte
     * @param evt 
     */
    private void fontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fontButtonActionPerformed
        // TODO add your handling code here:
        new FontStyleFrame("ChatFontSettings");
        try {
            SoundManager.play(Sound.FONT_STYLE);
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_fontButtonActionPerformed

    /**
     * Evento gerado pelo botçao precionado
     * @param evt 
     */
    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_formKeyPressed

    /**
     * Evento gerado pelo botão de seleção de emoticons
     * @param evt 
     */
    private void emoticonsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_emoticonsButtonActionPerformed
        // TODO add your handling code here:
        if (canInsertEmoticons) {
            emoticonsCode.add(inputMessage.getCaretPosition(), Emoticon.GRIN_CODE);

            characterRemaining--;

            characterNumberLabel.setText("" + characterRemaining);

            inputMessage.insertIcon(new ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/" + Emoticon.GRIN)));

            try {
                SoundManager.play(Sound.EMOTICONS);
            } catch (Exception ex) {
            }

        }
    }//GEN-LAST:event_emoticonsButtonActionPerformed

    /**
     * Evento gerado quando usuário digita mensagem de texto
     * @param evt 
     */
    private void inputMessageKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputMessageKeyPressed
        //   TODO add your handling code here:

        canInsertEmoticons = canInsert(evt);

    }//GEN-LAST:event_inputMessageKeyPressed

    /**
     * Evento gerado pela adição do emoticon "evil"
     * @param evt 
     */
    private void evilMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_evilMenuItemActionPerformed
        addEmoticon(Emoticon.EVILGRIN);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_evilMenuItemActionPerformed

    /**
     * Evento gerado pela adiçao do emoticon "wii"
     * @param evt 
     */
    private void wiiMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_wiiMenuItemActionPerformed
        // TODO add your handling code here:
        addEmoticon(Emoticon.WAII);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_wiiMenuItemActionPerformed

    /**
     * Evento gerado pelo emoticon "grin"
     * @param evt 
     */
    private void grinMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_grinMenuItemActionPerformed
        // TODO add your handling code here:
        addEmoticon(Emoticon.GRIN);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_grinMenuItemActionPerformed

    /**
     * Evento gerado pelo emoticon "happy"
     * @param evt 
     */
    private void happyMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_happyMenuItemActionPerformed
        // TODO add your handling code here:
        addEmoticon(Emoticon.HAPPY);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_happyMenuItemActionPerformed

    /**
     * Evento gerado pelo emoticon "smile"
     * @param evt 
     */
    private void smileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_smileMenuItemActionPerformed
        // TODO add your handling code here:
        addEmoticon(Emoticon.SMILE);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_smileMenuItemActionPerformed

    /**
     * Evento gerado pelo emoticon "surprise"
     * @param evt 
     */
    private void surprisedMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_surprisedMenuItemActionPerformed
        // TODO add your handling code here:
        addEmoticon(Emoticon.SURPRISED);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_surprisedMenuItemActionPerformed

    /**
     * Evento gerado pelo emoticon "tongue"
     * @param evt 
     */
    private void tongueMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tongueMenuItemActionPerformed
        // TODO add your handling code here:
        addEmoticon(Emoticon.TONGUE);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_tongueMenuItemActionPerformed

    /**
     * Evento gerado pelo emoticon "unhappy"
     * @param evt 
     */
    private void unhappyMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unhappyMenuItemActionPerformed
        // TODO add your handling code here:
        addEmoticon(Emoticon.UNHAPPY);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_unhappyMenuItemActionPerformed

    /**
     * Evento gerado pelo emoticon "wink"
     * @param evt 
     */
    private void winkMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_winkMenuItemActionPerformed
        // TODO add your handling code here:
        addEmoticon(Emoticon.WINK);
        log.info(myResources.getString("chat.log.emoticon"));
    }//GEN-LAST:event_winkMenuItemActionPerformed

    private void updateSettingsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateSettingsButtonActionPerformed
        // TODO add your handling code here:
        getTextSettings();
        setInputMessageSetStyle();
    }//GEN-LAST:event_updateSettingsButtonActionPerformed

    public void addEmoticon(String emoticonName) {


        try {
            // TODO add your handling code here:
            emoticonsCode.add(inputMessage.getCaretPosition(), Emoticon.getEmoticonCode(emoticonName));

            inputMessage.insertIcon(new ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/" + emoticonName)));

            SoundManager.play(Sound.EMOTICONS);
        } catch (Exception ex) {
        }
    }

    /**
     * inicializa uma lista que armazena os codigos dos emoticons
     */
    private void initEmoticonsCode() {
        for (int i = 0; i < 150; i++) {
            emoticonsCode.add(i, "");
        }
    }

    //usado para controlar teclas precionadas e comprimento de texto ou emoticons inseridos
    private boolean canInsert(KeyEvent evt) {

        int keyPressed = evt.getKeyCode();

        System.out.println("" + keyPressed);
        //colocar log
        if (Key.isKeyTypedValid(keyPressed)) {

            if (characterRemaining > 0 && characterRemaining <= 150) {

                if (keyPressed == Key.BACKSPACE) {
                    if (inputMessage.getCaretPosition() != 0) {
                        characterRemaining++;
                    }

                } else {
                    characterRemaining--;
                }

                characterNumberLabel.setText("" + characterRemaining);
                return true;
            } else if (inputMessage.getCaretPosition() != 0) {
                if (keyPressed == Key.BACKSPACE && characterRemaining == 0) {
                    characterRemaining++;
                    inputMessage.setEditable(true);
                    characterNumberLabel.setText("" + characterRemaining);
                    return true;
                } else {
                    inputMessage.setEditable(false);
                    return false;
                }

            }
        }
        return false;
    }

    /**
     * Evento que trata a mensagem recebida pelo usuário
     * @param message 
     */
    private void displayMessage(String message) {
        try {
            StringTokenizer msgReceived = new StringTokenizer(message, ServerSettings.marca);

            String name, separator, msg;

            friendName = msgReceived.nextToken();
            name = msgReceived.nextToken();
            separator = msgReceived.nextToken();
            msg = msgReceived.nextToken();

            if (friendName.equals("null")) {
                messageSentReceived = messageSentReceived.append("<br>"
                        + getTextWithFontSet(message));
                displayMessage.setText(header + messageSentReceived.toString() + body);
            }
        } catch (NoSuchElementException ex) {
        }
    }

    /**
     * Pega a mensagem
     * @param message 
     */
    public void getMessage(String message) {
        displayMessage(message);
    }

    /**
     * Pega o nome do usuário
     * @param 
     */
    public String getUserName() {
        return userName;
    }
    //retorna texto com a fonte corrigida como cor, tamanho...

    /**
     * Pega o texto com a fonte configurada
     * @param text
     * @return 
     */
    private String getTextWithFontSet(String text) {
        try {
            StringTokenizer msgReceived = new StringTokenizer(text, ServerSettings.marca);

            String name, separator, msg;

            friendName = msgReceived.nextToken();
            name = msgReceived.nextToken();
            separator = msgReceived.nextToken();
            msg = msgReceived.nextToken();



            msg = Emoticon.addEmoticonsToMessageReceived(msg);//adiciona emoticon a mensagem

            if (userName.equals(name)) {
                return myNameFont.setFont(name,
                        myNameFont.color,
                        myNameFont.STYLE,
                        myNameFont.size,
                        myNameFont.BOLD,
                        myNameFont.ITALIC,
                        myNameFont.UNDERLINE)
                        + mySeparatorFont.setFont(separator,
                        mySeparatorFont.color,
                        mySeparatorFont.STYLE,
                        mySeparatorFont.size,
                        mySeparatorFont.BOLD,
                        mySeparatorFont.ITALIC,
                        mySeparatorFont.UNDERLINE)
                        + myTextFont.setFont(msg,
                        myTextFont.color,
                        myTextFont.STYLE,
                        myTextFont.size,
                        myTextFont.BOLD,
                        myTextFont.ITALIC,
                        myTextFont.UNDERLINE);
            } else {
                return friendNameFont.setFont(name,
                        friendNameFont.color,
                        friendNameFont.STYLE,
                        friendNameFont.size,
                        friendNameFont.BOLD,
                        friendNameFont.ITALIC,
                        friendNameFont.UNDERLINE)
                        + friendSeparatorFont.setFont(
                        separator,
                        friendSeparatorFont.color,
                        friendSeparatorFont.STYLE,
                        friendSeparatorFont.size,
                        friendSeparatorFont.BOLD,
                        friendSeparatorFont.ITALIC,
                        friendSeparatorFont.UNDERLINE)
                        + friendTextFont.setFont(msg,
                        friendTextFont.color,
                        friendTextFont.STYLE,
                        friendTextFont.size,
                        friendTextFont.BOLD,
                        friendTextFont.ITALIC,
                        friendTextFont.UNDERLINE);
            }
        } catch (NoSuchElementException exeception) {
            return "";
        }
    }

    /**
     * Metodo que pega as configurações do texto
     */
    public void getTextSettings() {

        //armazendando configurações na array list
        SettingsFile.connect();

        myNameFont.color = SettingsFile.getSetting(("my_name"), "color");
        myNameFont.STYLE = SettingsFile.getSetting(("my_name"), "style");
        myNameFont.size = Integer.parseInt(SettingsFile.getSetting(("my_name"), "size"));
        myNameFont.BOLD = Boolean.parseBoolean(SettingsFile.getSetting(("my_name"), "BOLD"));
        myNameFont.ITALIC = Boolean.parseBoolean(SettingsFile.getSetting(("my_name"), "ITALIC"));
        myNameFont.UNDERLINE = Boolean.parseBoolean(SettingsFile.getSetting(("my_name"), "UNDERLINE"));

        mySeparatorFont.color = SettingsFile.getSetting(("my_separator"), "color");
        mySeparatorFont.STYLE = SettingsFile.getSetting(("my_separator"), "style");
        mySeparatorFont.size = Integer.parseInt(SettingsFile.getSetting(("my_separator"), "size"));
        mySeparatorFont.BOLD = Boolean.parseBoolean(SettingsFile.getSetting(("my_separator"), "BOLD"));
        mySeparatorFont.ITALIC = Boolean.parseBoolean(SettingsFile.getSetting(("my_separator"), "ITALIC"));
        mySeparatorFont.UNDERLINE = Boolean.parseBoolean(SettingsFile.getSetting(("my_separator"), "UNDERLINE"));

        myTextFont.color = SettingsFile.getSetting(("my_text"), "color");
        myTextFont.STYLE = SettingsFile.getSetting(("my_text"), "style");
        myTextFont.size = Integer.parseInt(SettingsFile.getSetting(("my_text"), "size"));
        myTextFont.BOLD = Boolean.parseBoolean(SettingsFile.getSetting(("my_text"), "BOLD"));
        myTextFont.ITALIC = Boolean.parseBoolean(SettingsFile.getSetting(("my_text"), "ITALIC"));
        myTextFont.UNDERLINE = Boolean.parseBoolean(SettingsFile.getSetting(("my_text"), "UNDERLINE"));


        friendNameFont.color = SettingsFile.getSetting(("friend_name"), "color");
        friendNameFont.STYLE = SettingsFile.getSetting(("friend_name"), "style");
        friendNameFont.size = Integer.parseInt(SettingsFile.getSetting(("friend_name"), "size"));
        friendNameFont.BOLD = Boolean.parseBoolean(SettingsFile.getSetting(("friend_name"), "BOLD"));
        friendNameFont.ITALIC = Boolean.parseBoolean(SettingsFile.getSetting(("friend_name"), "ITALIC"));
        friendNameFont.UNDERLINE = Boolean.parseBoolean(SettingsFile.getSetting(("friend_name"), "UNDERLINE"));

        friendSeparatorFont.color = SettingsFile.getSetting(("friend_separator"), "color");
        friendSeparatorFont.STYLE = SettingsFile.getSetting(("friend_separator"), "style");
        friendSeparatorFont.size = Integer.parseInt(SettingsFile.getSetting(("friend_separator"), "size"));
        friendSeparatorFont.BOLD = Boolean.parseBoolean(SettingsFile.getSetting(("friend_separator"), "BOLD"));
        friendSeparatorFont.ITALIC = Boolean.parseBoolean(SettingsFile.getSetting(("friend_separator"), "ITALIC"));
        friendSeparatorFont.UNDERLINE = Boolean.parseBoolean(SettingsFile.getSetting(("friend_separator"), "UNDERLINE"));

        friendTextFont.color = SettingsFile.getSetting(("friend_text"), "color");
        friendTextFont.STYLE = SettingsFile.getSetting(("friend_text"), "style");
        friendTextFont.size = Integer.parseInt(SettingsFile.getSetting(("friend_text"), "size"));
        friendTextFont.BOLD = Boolean.parseBoolean(SettingsFile.getSetting(("friend_text"), "BOLD"));
        friendTextFont.ITALIC = Boolean.parseBoolean(SettingsFile.getSetting(("friend_text"), "ITALIC"));
        friendTextFont.UNDERLINE = Boolean.parseBoolean(SettingsFile.getSetting(("friend_text"), "UNDERLINE"));

        SettingsFile.desconnect();

    }

    /**
     * Metodo para configurar a fonte para o inputMessage
     */
    private void initFontStyles() {
        myNameFont = new FontHTML();
        mySeparatorFont = new FontHTML();
        myTextFont = new FontHTML();

        friendNameFont = new FontHTML();
        friendSeparatorFont = new FontHTML();
        friendTextFont = new FontHTML();
    }

    /**
     * Metodo para configurar o estilo da mensagem
     */
    private void setInputMessageSetStyle() {
        String fontName = myTextFont.STYLE;
        int size = myTextFont.size * 5;
        int R, G, B;
        try {
            //pega hexadecimal string e transforma em um valor int
            R = Integer.valueOf(myTextFont.color.substring(0, 2), 16).intValue();
            G = Integer.valueOf(myTextFont.color.substring(2, 4), 16).intValue();
            B = Integer.valueOf(myTextFont.color.substring(4, 6), 16).intValue();
            inputMessage.setFont(new Font(fontName, Font.BOLD, size));
            inputMessage.setForeground(new Color(R, G, B));
            //CONSERTAR !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        } catch (StringIndexOutOfBoundsException exception) {
            inputMessage.setFont(new Font(fontName, Font.PLAIN, size));
            inputMessage.setForeground(new Color(0, 0, 0));
        }

    }

    /**
     * Pega o estilo da mensagem configurada
     * @param style
     * @return 
     */
    private int getStyle(String style) {
        if (style.equals("BOLD")) {
            return Font.BOLD;
        } else if (style.equals("ITALIC")) {
            return Font.ITALIC;
        } else {
            return Font.PLAIN;
        }
    }
    /**
     * Inicializa componentes gerados pelo netbeans
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu addMenu;
    private javax.swing.JLabel characterNumberLabel;
    private javax.swing.JLabel characterRemainingLabel;
    private javax.swing.JPanel chatBackgroundPanel;
    private javax.swing.JMenuBar chatMenu;
    private javax.swing.JTextPane displayMessage;
    private javax.swing.JButton emoticonsButton;
    private javax.swing.JMenuItem evilMenuItem;
    private javax.swing.JButton fontButton;
    private javax.swing.JMenu fontMenu;
    private javax.swing.JMenuItem grinMenuItem;
    private javax.swing.JMenuItem happyMenuItem;
    private javax.swing.JTextPane inputMessage;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton sendButton;
    private javax.swing.JMenu settingsMenu;
    private javax.swing.JMenuItem smileMenuItem;
    private javax.swing.JMenuItem styleMenuItem;
    private javax.swing.JMenuItem surprisedMenuItem;
    private javax.swing.JMenu textMenu;
    private javax.swing.JMenuItem tongueMenuItem;
    private javax.swing.JMenuItem unhappyMenuItem;
    private javax.swing.JButton updateSettingsButton;
    private javax.swing.JMenuItem wiiMenuItem;
    private javax.swing.JMenuItem winkMenuItem;
    // End of variables declaration//GEN-END:variables

    /**
     * Metodo que inicia o usuário
     */
    private void initUser() {
        userName = JOptionPane.showInputDialog(myResources.getString("chat.prompt.login"));
    }
}
